package com.xrun.risk.service.process.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xrun.cmap.WfMapUtils;
import com.xrun.common.constant.ThirdTypeConstants;
import com.xrun.ocenengine.dto.vo.AgentTokenAndTypeVo;
import com.xrun.ocenengine.util.qianChuan.QCMeterApiUtil;
import com.xrun.risk.domain.WfRiskDeleteTask;
import com.xrun.risk.domain.WfRiskDeleteTaskAdter;
import com.xrun.risk.domain.WfRiskDeleteTaskAdterContentDetail;
import com.xrun.risk.mapper.WfRiskDeleteTaskAdterContentDetailMapper;
import com.xrun.risk.service.process.Process;
import com.xrun.risk.util.AdMaterialUtilV2;
import com.xrun.risk.util.QianchuanMaterialUtilV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class VideoProcessImpl implements Process {
    @Autowired
    private QianchuanMaterialUtilV2 qianchuanMaterialUtilV2;
    @Autowired
    private WfRiskDeleteTaskAdterContentDetailMapper wfRiskDeleteTaskAdterContentDetailMapper;
    @Autowired
    private AdMaterialUtilV2 adMaterialUtilV2;
    @Autowired
    private QCMeterApiUtil qcMeterApiUtil;

    @Override
    public Object execute(WfRiskDeleteTask wfRiskDeleteTask,
                          WfRiskDeleteTaskAdter record,
                          AgentTokenAndTypeVo vo) {

        //获取所有素材id
        List<String> idsAd = this.getVideoIds(WfMapUtils.get(vo.getTokenTableId()),
                record.getAdvertiserId() + "", vo.getThirdType());
        if (CollectionUtil.isEmpty(idsAd)) {
            return null;
        }
        //构造对象
        Map<String, WfRiskDeleteTaskAdterContentDetail> contentDetails = WfRiskDeleteTaskAdterContentDetail.getListEntityContent(
                idsAd, record, vo, wfRiskDeleteTask, "VIDEO");

        //巨量删除
        List<WfRiskDeleteTaskAdterContentDetail> results = this.videoDel(vo.getTokenTableId(), record.getAdvertiserId() + "",
                idsAd, contentDetails, vo.getThirdType());

        //本地存储
        wfRiskDeleteTaskAdterContentDetailMapper.batchInsert(results);

        return null;
    }


    /**
     * 获取所有图片id
     *
     * @param accessToken
     * @param accountId
     * @param thirdType
     * @return
     */
    public List<String> getVideoIds(String accessToken, String accountId, String thirdType) {
        List<String> objects = new ArrayList<>();
        int currentPage = 1;
        int totalPage = 1;

        do {
            JSONObject jsonObject = null;
            if (ThirdTypeConstants.QIANCHAN.equals(thirdType)) {
                jsonObject = qianchuanMaterialUtilV2.listAdMaterialVideoByAccountId(
                        accessToken, accountId, currentPage, 100, null,
                        null, null, null, null);
            } else {
                jsonObject = adMaterialUtilV2.listAdMaterialVideoByAccountId(
                        accessToken, accountId, currentPage, 100, null,
                        null, null, null, null);
            }

            totalPage = jsonObject.getJSONObject("data").getJSONObject("page_info").getIntValue("total_page");
            currentPage++;
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
            if (CollectionUtil.isNotEmpty(jsonArray)) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    objects.add(jsonArray.getJSONObject(i).getString("id"));
                }
            }
        } while (currentPage <= totalPage);

        return objects;
    }


    /**
     * qc 删除数据
     *
     * @param tokenTableId
     * @param thirdType
     * @return
     */
    private List<WfRiskDeleteTaskAdterContentDetail> videoDel(String tokenTableId, String accountId, List<String> ids, Map<String, WfRiskDeleteTaskAdterContentDetail> imageMap, String thirdType) {
        List<List<String>> split = ListUtil.split(ids, 100);
        for (List<String> splitIds : split) {
            JSONObject jsonObject = null;
            if (ThirdTypeConstants.AD.equals(thirdType)) {
                jsonObject = adMaterialUtilV2.videoDelete(WfMapUtils.get(tokenTableId), accountId, splitIds);
            } else {
                jsonObject = qcMeterApiUtil.videoDelete(WfMapUtils.get(tokenTableId), accountId, 0, splitIds);
            }

            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("fail_video_ids");
            if (CollectionUtil.isNotEmpty(jsonArray)) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    String imageId = jsonArray.getString(i);
                    splitIds.remove(imageId );
                    WfRiskDeleteTaskAdterContentDetail one = imageMap.get(imageId);
                    if (one != null) {
                        one.setClearStatus("2");//2清理失败
                        one.setFailReason(jsonObject.getString("message"));
                        imageMap.put(imageId, one);
                    }
                }
            }

            if (CollectionUtil.isNotEmpty(splitIds)){
                for (String splitId : splitIds) {
                    WfRiskDeleteTaskAdterContentDetail one = imageMap.get(splitId);
                    one.setClearStatus("1");//1清理成功
                    imageMap.put(splitId, one);
                }
            }

        }
        return new ArrayList<>(imageMap.values());
    }
}